package school.valon.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil {
	private final static Properties properties = new Properties();
	private static String smtpUserEmail;
	private static String smtpUserPassword;
	
	static {
		try {
			FileReader fileReader = new FileReader(new File(Thread.currentThread().getContextClassLoader().getResource("config/mailconfig.properties").toURI()));
			properties.load(fileReader);
			smtpUserEmail = properties.getProperty("mail.smtp.user");
			smtpUserPassword = properties.getProperty("mail.smtp.password");
			fileReader.close();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}

	public static void sendMail(String to, String messageSubject, String messageContent) {
		Session session = Session.getDefaultInstance(properties,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(smtpUserEmail, smtpUserPassword);
					}
				});

		try {
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(smtpUserEmail));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(to));
			message.setSubject(messageSubject);
			message.setText(messageContent);
 			Transport.send(message);

			System.out.println("Done");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
